import numpy as np
from sklearn.cluster import KMeans


def loadData(filePath):
    # 读写方式打开文件
    fr = open(filePath, 'r+')
    # 一次读取整个文件
    lines = fr.readlines()
    retData = []
    retCityName = []
    for line in lines:
        items = line.strip().split(",")
        retCityName.append(items[0])
        retData.append([float(items[i]) for i in range(1, len(items))])
    return retData, retCityName


if __name__ == '__main__':
    # 31省市居民家庭消费水平-city
    data, cityName = loadData('city.txt')
    # 聚类中心的个数
    km = KMeans(n_clusters=4)
    # 计算簇中心并分配序号
    label = km.fit_predict(data)
    # 聚类中心点的数值加和 平均消费水平
    expenses = np.sum(km.cluster_centers_, axis=1)
    # print(expenses)
    # 按label将城市分成设定的簇
    CityCluster = [[], [], [], []]
    # 输出城市
    for i in range(len(cityName)):
        CityCluster[label[i]].append(cityName[i])
    # 输出平均花费
    for i in range(len(CityCluster)):
        print("Expenses:%.2f" % expenses[i])
        print(CityCluster[i])